<template>
	<text v-if="visible" class="cuIcon-scan text-lg" @click="scanCode"></text>
</template>

<script>
// #ifdef APP-PLUS
import permision from '@/platforms/app-plus/permission.js';
// #endif
import util from '@/common/util'
import http from '@/common/http'
export default {
	data() {
		return {};
	},
	props: {
	  visible: {
	    type: Boolean,
	    default: true
	  }	 
	},
	methods: {
		async scanCode(callback) { 			
			var that = this;
			// #ifdef APP-PLUS
			let status = await this.checkPermission();
			if (status !== 1) {
			    return;
			}
			// #endif			
			// 只允许通过相机扫码
			uni.scanCode({
				onlyFromCamera: true,
				success: function(res) { 
					//console.log('条码类型：' + res.scanType);
					if(typeof(callback) =="function"){
						callback(res.result) 
					} else{   
						util.msg(res.result);   
					}
					
					/* if (res.result && res.result.indexOf(util.baseUrl) != -1) {
						//发起ajax请求
						http.get(res.result).then(res => {
							util.msg(res.msg);
							if (res.status) {
							} else {
							}
						});
					} */
				},
				fail: err => {
					// #ifdef MP
					uni.getSetting({
						success: res => {
							let authStatus = res.authSetting['scope.camera'];
							if (!authStatus) {
								uni.showModal({
									title: '授权失败',
									content: '需要使用您的相机，请在设置界面打开相关权限',
									success: res => {
										if (res.confirm) {
											uni.openSetting();
										}
									}
								});
							}
						}
					});
					// #endif
				}
			});
		},
		// #ifdef APP-PLUS
		async checkPermission(code) {
			let status = permision.isIOS ? await permision.requestIOS('camera') : await permision.requestAndroid('android.permission.CAMERA');

			if (status === null || status === 1) {
				status = 1;
			} else {
				uni.showModal({
					content: '需要相机权限',
					confirmText: '设置',
					success: function(res) {
						if (res.confirm) {
							permision.gotoAppSetting();
						}
					}
				});
			}
			return status;
		}
		// #endif
	}
};
</script>

<style lang="scss"></style>
